package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.tingshu.album.mapper.*;
import com.atguigu.tingshu.album.service.BaseCategoryService;
import com.atguigu.tingshu.common.cache.GuiGuCache;
import com.atguigu.tingshu.model.album.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@SuppressWarnings({"all"})
public class BaseCategoryServiceImpl extends ServiceImpl<BaseCategory1Mapper, BaseCategory1> implements BaseCategoryService {

    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;

    @Autowired
    private BaseCategory2Mapper baseCategory2Mapper;

    @Autowired
    private BaseCategory3Mapper baseCategory3Mapper;

    @Autowired
    private BaseCategoryViewMapper baseCategoryViewMapper;

    @Autowired
    private BaseAttributeMapper baseAttributeMapper;


    /**
     * 查询所有分类（1、2、3级分类）
     * 思路：查询封装1，2，3级分类视图
     *
     * @return
     */
    @Override
    @GuiGuCache(prefix = "category:allcategory:")
    public List<JSONObject> getBaseCategoryList() {
        //1.查询视图得到所有分类视图数据
        List<BaseCategoryView> allCategoryList = baseCategoryViewMapper.selectList(null);
        //2.处理一级分类列表
        //2.1 按照1级分类ID进行分组 得到Map集合 Key:1级分类ID  Val：对应1级分类列表
        Map<Long, List<BaseCategoryView>> category1Map = allCategoryList.stream()
                .collect(Collectors.groupingBy(BaseCategoryView::getCategory1Id));

        //2.2 遍历一级分类Map得到一级分类ID及名称
        List<JSONObject> list = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(category1Map)) {
            for (Map.Entry<Long, List<BaseCategoryView>> entry1 : category1Map.entrySet()) {
                //2.2.1 获取一级分类ID
                Long category1Id = entry1.getKey();
                //2.2.2 获取一级分类名称
                String category1Name = entry1.getValue().get(0).getCategory1Name();
                //2.2.3 构建一级分类JSON对象
                JSONObject jsonObject1 = new JSONObject();
                jsonObject1.put("categoryId", category1Id);
                jsonObject1.put("categoryName", category1Name);

                //3. 在某个一级分类中处理二级分类列表
                //3.1 获取一级分类集合，对集合进行分组-分组字段为：二级分类ID 得到“二级分类”Map Map的Key:二级分类ID  Val："二级分类"集合
                Map<Long, List<BaseCategoryView>> category2Map = entry1.getValue()
                        .stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));
                //3.2 遍历"二级分类"Map得到二级分类信息
                //3.2.3 创建二级分类JSON对象集合
                List<JSONObject> jsonObject2List = new ArrayList<>();
                for (Map.Entry<Long, List<BaseCategoryView>> entry2 : category2Map.entrySet()) {

                    //3.2.1 获取二级分类ID
                    Long category2Id = entry2.getKey();
                    //3.2.2 获取二级分类名称
                    String category2Name = entry2.getValue().get(0).getCategory2Name();


                    //3.2.4 构建二级分类JSON对象 将JSON对象加入到二级分类JSON对象集合中
                    JSONObject jsonObject2 = new JSONObject();
                    jsonObject2.put("categoryId", category2Id);
                    jsonObject2.put("categoryName", category2Name);
                    jsonObject2List.add(jsonObject2);
                    //4. 在某个二级分类中处理三级分类列表
                    //4.1 遍历“二级分类”列表得到当前二级分类下包含“三级”分类
                    List<JSONObject> jsonObject3List = new ArrayList<>();
                    for (BaseCategoryView baseCategoryView : entry2.getValue()) {
                        //4.1.1 获取三级分类ID
                        Long category3Id = baseCategoryView.getCategory3Id();
                        //4.1.2 获取三级分类名称
                        String category3Name = baseCategoryView.getCategory3Name();
                        //4.1.3 构建三级分类JSON对象
                        JSONObject jsonObject3 = new JSONObject();
                        jsonObject3.put("categoryId", category3Id);
                        jsonObject3.put("categoryName", category3Name);
                        //4.1.4 将三级分类JSON对象装入集合中
                        jsonObject3List.add(jsonObject3);
                    }
                    //4.2 将三级分类集合放入到二级分类JSON对象中"categoryChild”属性中
                    jsonObject2.put("categoryChild", jsonObject3List);
                }
                //3.2.5 将二级JSON对象集合放入到一级分类分类对象中“categoryChild”属性中
                jsonObject1.put("categoryChild", jsonObject2List);

                list.add(jsonObject1);
            }
        }
        return list;
    }


    /**
     * 根据一级分类Id获取分类标签以及标签值
     *
     * @param category1Id
     * @return
     */
    @Override
    @GuiGuCache(prefix="category:baseAttribute:") //将该方法执行查库结果放入缓存，采用分布式锁杜绝缓存击穿
    public List<BaseAttribute> getAttributeByCategory1Id(Long category1Id) {
        //获取标签持久层Mapper对象,调用持久层方法获取标签列表
        return baseAttributeMapper.getAttributeByCategory1Id(category1Id);
    }

    @Override
    @GuiGuCache(prefix = "category:categoryview:")
    public BaseCategoryView getCategoryView(Long category3Id) {
        return baseCategoryViewMapper.selectById(category3Id);
    }


    /**
     * 根据1级分类ID查询该分类下前7个置顶3级分类列表
     *
     * @param category1Id
     * @return
     */
    @Override
    @GuiGuCache(prefix = "category:topcategory3:")
    public List<BaseCategory3> getTopBaseCategory3(Long category1Id) {
        //1.根据1级分类ID获取二级分类列表
        LambdaQueryWrapper<BaseCategory2> category2LambdaQueryWrapper = new LambdaQueryWrapper<>();
        category2LambdaQueryWrapper.eq(BaseCategory2::getCategory1Id, category1Id);
        category2LambdaQueryWrapper.select(BaseCategory2::getId);
        List<BaseCategory2> baseCategory2List = baseCategory2Mapper.selectList(category2LambdaQueryWrapper);
        //2.获取二级分类ID列表
        if (CollectionUtil.isNotEmpty(baseCategory2List)) {
            List<Long> baseCategory2IdList = baseCategory2List.stream().map(BaseCategory2::getId).collect(Collectors.toList());
            //3.根据二级分类ID列表查询三级分类
            LambdaQueryWrapper<BaseCategory3> queryWrapper = new LambdaQueryWrapper<>();
            //3.1 where category2_id in (101, 102, 103)
            queryWrapper.in(BaseCategory3::getCategory2Id, baseCategory2IdList);
            //3.2 置顶3级分类
            queryWrapper.eq(BaseCategory3::getIsTop, 1);
            //3.3 排序
            queryWrapper.orderByAsc(BaseCategory3::getOrderNum);
            //3.4 top7
            queryWrapper.last("limit 7");
            return baseCategory3Mapper.selectList(queryWrapper);
        }
        return null;
    }

    /**
     * 根据1级分类ID查询包含二级分类以及三级分类
     *
     * @param category1Id
     * @return
     */
    @Override
    @GuiGuCache(prefix = "category:categoryby1Id:")
    public JSONObject getBaseCategoryListByCategory1Id(Long category1Id) {
        //1.封装一级分类对象
        LambdaQueryWrapper<BaseCategoryView> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BaseCategoryView::getCategory1Id, category1Id);
        List<BaseCategoryView> category1List = baseCategoryViewMapper.selectList(queryWrapper);
        BaseCategoryView baseCategoryView = category1List.get(0);
        //1.1 封装一级分类对象
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("categoryId", baseCategoryView.getCategory1Id());
        jsonObject1.put("categoryName", baseCategoryView.getCategory1Name());
        //2.处理一级分类下包含二级分类列表
        //2.1 对“一级分类集合”中二级分类ID进行分组
        Map<Long, List<BaseCategoryView>> category2Map =
                category1List.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));
        if (CollectionUtil.isNotEmpty(category2Map)) {
            List<JSONObject> jsonObjects2List = new ArrayList<>();
            for (Map.Entry<Long, List<BaseCategoryView>> entry2 : category2Map.entrySet()) {
                //2.2 封装二级分类JSON对象
                Long category2Id = entry2.getKey();
                String category2Name = entry2.getValue().get(0).getCategory2Name();
                JSONObject jsonObject2 = new JSONObject();
                jsonObject2.put("categoryId", category2Id);
                jsonObject2.put("categoryName", category2Name);
                jsonObjects2List.add(jsonObject2);
                //3.处理二级分类下包含三级分类列表
                List<JSONObject> jsonObjects3List = new ArrayList<>();
                for (BaseCategoryView categoryView : entry2.getValue()) {
                    //3.1 构建三级分类JSON对象
                    JSONObject jsonObject3 = new JSONObject();
                    jsonObject3.put("categoryId", categoryView.getCategory3Id());
                    jsonObject3.put("categoryName", categoryView.getCategory3Name());
                    jsonObjects3List.add(jsonObject3);
                }
                //3.2 将三级分类JSON对象集合将入二级分类对象"categoryChild"属性中
                jsonObject2.put("categoryChild", jsonObjects3List);
            }
            //2.3 将二级分类JSON对象集合加入到一级分类对象"categoryChild"属性中
            jsonObject1.put("categoryChild", jsonObjects2List);
        }
        return jsonObject1;
    }
}
